package service

import (
	"duoke/model"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/orm"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
)

var Reward = new(rewardService)

type rewardService struct{}

func (s *rewardService) GetById(id int, field string) (*tables.UserReward, error) {
	reward := new(tables.UserReward)
	has, err := orm.Db.ID(id).Cols(field).Get(reward)
	if err != nil {
		return nil, err
	}
	if !has {
		return nil, errors.New("该记录不存在")
	}
	return reward, nil
}

func (s *rewardService) List(c *gin.Context, where string, limit int, field string) ([]tables.UserReward, float64, error) {
	accountR, _ := Request.Account(c)
	//判断子账户
	query := orm.Db.Desc("id").Cols(field).Limit(limit).Where(where)
	if accountR.Role == "goods" {
		query = query.Where("goods_id IN(?)", accountR.GoodsIds)
	} else {
		query = query.Where("acid =?", accountR.Id)
	}
	list := make([]tables.UserReward, 0)
	err := query.Find(&list)
	if err != nil {
		return nil, 0, err
	}
	userReward := new(tables.UserReward)
	query2 := orm.Db.Where(where)
	if accountR.Role == "goods" {
		query2 = query2.Where("goods_id IN(?)", accountR.GoodsIds)
	} else {
		query2 = query2.Where("acid =?", accountR.Id)
	}
	totalAmount, err := query2.Sum(userReward, "amount")
	return list, totalAmount, nil
}
func (s *rewardService) Page(c *gin.Context, req model.ReqList, where string, field string) ([]tables.UserReward, int64, float64, error) {
	accountR, _ := Request.Account(c)
	// 分页
	offset := (req.PageNo - 1) * req.PageSize
	//判断子账户
	query := orm.Db.Desc("id").Cols(field).Limit(req.PageSize, offset).Where(where)
	if accountR.Role == "goods" {
		query = query.Where("goods_id IN(?)", accountR.GoodsIds)
	} else {
		query = query.Where("acid =?", accountR.Id)
	}
	list := make([]tables.UserReward, 0)
	total, err := query.FindAndCount(&list)
	if err != nil {
		return nil, 0, 0, err
	}
	userReward := new(tables.UserReward)
	query2 := orm.Db.Where(where)
	if accountR.Role == "goods" {
		query2 = query2.Where("goods_id IN(?)", accountR.GoodsIds)
	} else {
		query2 = query2.Where("acid =?", accountR.Id)
	}
	totalAmount, err := query2.Sum(userReward, "amount")
	return list, total, totalAmount, nil
}
func (s *rewardService) Send(c *gin.Context, atype int, acid int, goodsId int, goodsTitle string, userId int, amount float64, orderNo string, fromId int, remark string, isSend bool) (bool, error) {
	orderNo = "sp" + orderNo + "u" + gconv.String(userId) + "f" + gconv.String(fromId)
	user := new(tables.GoodsUser)
	has, err := orm.Db.Where("user_id =? AND goods_id =?", userId, goodsId).Get(user)
	if err != nil {
		return false, err
	}
	if !has {
		return false, errors.New("奖励用户不存在")
	}
	reward := new(tables.UserReward)
	count, err := orm.Db.Where("acid = ? AND type =? AND goods_id =? AND user_id =? AND order_no =?", acid, atype, goodsId, userId, orderNo).Count(reward)
	if err != nil {
		return false, err
	}
	if count > 0 {
		return false, errors.New("该奖励记录已存在")
	}
	// 使用退款渠道发放
	goods, err := Goods.GetById(goodsId, "")
	if err != nil {
		return false, err
	}
	if gconv.Int(goods.Config["is_send_refund_redbag"]) == 1 {
		// 获取奖励人的购买订单
		where := "goods_id =" + gconv.String(goodsId) + " "
		where += "AND user_id =" + gconv.String(userId) + " "
		where += "AND pay_state = 1 "
		where += "AND refund_state = 0 "
		order, err := Order.GetByWhere(where, "")
		if err != nil {
			return false, err
		}
		if order.Id == 0 {
			return false, errors.New("发放人没有已支付订单记录，无法退款发放奖励")
		}
		if amount > gconv.Float64(order.PayAmount) {
			return false, errors.New("奖励金额大于订单支付金额")
		}
		isSuccess, err := WechatPay.RewardRefund(c, amount, gconv.Float64(order.PayAmount), orderNo)
		if err != nil {
			return false, err
		}
		if isSuccess {
			return true, nil
		}
		return false, err
	}
	reward.Acid = acid
	reward.GoodsId = goodsId
	reward.GoodsTitle = goodsTitle
	reward.Type = atype
	reward.UserId = userId
	reward.OrderNo = orderNo
	reward.Openid = user.Openid
	reward.Nickname = user.Nickname
	reward.Avatar = user.Avatar
	reward.Amount = gconv.String(amount)
	reward.FromId = fromId
	reward.Remark = remark
	affected, err := orm.Db.Insert(reward)
	if err != nil {
		return false, err
	}
	if affected == 0 {
		return false, errors.New("创建奖励记录失败")
	}
	if isSend {
		//v2付款到零钱接口，已废弃
		//isSuccess, err := WechatPay.TransferV2(user.Openid, amount, orderNo, remark)
		//if err != nil {
		//	reward.Remark = err.Error()
		//	_, _ = orm.Db.ID(reward.Id).Update(reward)
		//	return false, err
		//}
		//if !isSuccess {
		//	reward.Remark = "零钱发放失败"
		//	_, _ = orm.Db.ID(reward.Id).Update(reward)
		//	return false, errors.New("零钱发放失败")
		//} else {
		//	reward.State = 1
		//	_, _ = orm.Db.ID(reward.Id).Update(reward)
		//}
		fmt.Println(reward)
		isSuccess, err := WechatPay.TransferV3(c, reward.Openid, gconv.Float64(reward.Amount), reward.OrderNo, reward.Remark)
		if err != nil {
			reward.FailMsg = err.Error()
			_, _ = orm.Db.ID(reward.Id).Update(reward)
			return false, err
		}
		if isSuccess {
			reward.State = 1
			_, _ = orm.Db.ID(reward.Id).Update(reward)
		} else {
			reward.FailMsg = "零钱发放失败"
			_, _ = orm.Db.ID(reward.Id).Update(reward)
			return false, errors.New("零钱发放失败")
		}
	}
	return true, nil
}
